package com.dg.cuckoo.admin.service.impl;

import com.dg.cuckoo.admin.dto.basicInformation.constructionUnit.ConstructionUnitDto;
import com.dg.cuckoo.admin.dto.basicInformation.label.OneLabelDto;
import com.dg.cuckoo.admin.dto.basicInformation.label.TwoLabelDto;
import com.dg.cuckoo.admin.dto.basicInformation.permissionSettings.UnitTypeDto;
import com.dg.cuckoo.admin.dto.other.FileDto;
import com.dg.cuckoo.admin.dto.basicInformation.projectInformation.TheLabelDto;
import com.dg.cuckoo.admin.dto.basicInformation.projectInformation.TheUnitDto;
import com.dg.cuckoo.admin.dto.basicInformation.projectInformation.BasicProjectDto;
import com.dg.cuckoo.admin.repository.*;
import com.dg.cuckoo.admin.service.ProjectInfoServer;
import com.dg.cuckoo.admin.vo.FreeVo;
import com.dg.cuckoo.admin.vo.FreeVoT;
import com.dg.cuckoo.common.utils.Oss;
import com.dg.cuckoo.common.utils.PageModel;
import com.dg.cuckoo.core.ServiceException;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class ProjectInfoServerimpl implements ProjectInfoServer {

    @Autowired
    private BasicProjectRepository repository;
    @Autowired
    private FileRepository fileRepository;
    @Autowired
    private TheLabelRepository theLabelRepository;
    @Autowired
    private TheUnitRepository theUnitRepository;
    @Autowired
    private UnitTypeRepository unitTypeRepository;
    @Autowired
    private ConstructionRepository constructionRepository;
    @Autowired
    private OneLabelRepository oneLabelRepository;
    @Autowired
    private TwoLableRepository twoLableRepository;


    @Transactional
    @Override
    public void save(BasicProjectDto dto, MultipartFile[] file, String[] labels, String[] units) throws Exception {
        saveCheck(dto);

        BasicProjectDto save = repository.save(dto);

        if (units != null) {
            unitSave(units, save.getId());
        }

        if (labels != null) {
            saveLabel(labels, save.getId());
        }

        if (file != null) {
            //fileSave(file, save.getId());
            powerfulFileSave(file, save.getId());
        }

    }

    @Transactional
    @Override
    public void delect(String id) {
        if (id == null) {
            throw new ServiceException("请选择要删除的项目");
        }
        repository.deleteById(id);
        delects(id);
    }

    @Transactional
    @Override
    public void update(BasicProjectDto dto, MultipartFile[] file, String[] labels, String[] units, String id) throws Exception {
        if (id == null) {
            throw new ServiceException("请选择要删除的项目");
        }

        dto.setId(id);
        repository.save(dto);

        if (units != null) {
            List<TheUnitDto> byByMark = theUnitRepository.findByByMark(id);
            theUnitRepository.deleteAll(byByMark);
            unitSave(units, id);
        }

        if (labels != null) {
            List<TheLabelDto> byByMark = theLabelRepository.findByByMark(id);
            theLabelRepository.deleteAll(byByMark);
            saveLabel(labels, id);
        }

        if (file != null) {
            List<FileDto> byByMark = fileRepository.findByByMark(id);
            fileRepository.deleteAll(byByMark);
            powerfulFileSave(file, id);
        }
    }

    @Override
    public String openInfo(String id) {
        if (id == null) {
            throw new ServiceException("去选择要查看的项目");
        }
        BasicProjectDto dto = repository.findById(id).get();
        List<FileDto> files = fileRepository.findByByMark(id);

        List<TheUnitDto> units = theUnitRepository.findByByMark(id);
        List<String> unit = new ArrayList<>();
        for (TheUnitDto d : units) {
            unit.add(d.getUnit());
        }

        List<TheLabelDto> labels = theLabelRepository.findByByMark(id);
        List<String> label = new ArrayList<>();
        for (TheLabelDto d : labels) {
            label.add(d.getLable());
        }

        JSONObject json = new JSONObject();
        json.put("dto", dto);        //项目具体信息
        json.put("files", files);    //项目的附件信息
        json.put("units", unit);    //项目所有建设单位名称
        json.put("labels", label);  //项目所有标签名称
        return json.toString();
    }

    @Override
    public String clickUnitInfo() {
        JSONObject json = new JSONObject();
        List<String> freeName=new ArrayList<>();
        List<UnitTypeDto> all = unitTypeRepository.findAll();
        List<FreeVo> freeVos=new ArrayList<>();
        for(UnitTypeDto u:all){
            FreeVo freeVo = new FreeVo();
            freeVo.setConstructionName(u.getTypeName());
            freeVo.setDtos(constructionRepository.findByUnitType(u.getTypeName()));
            freeName.add(u.getTypeName());
            freeVos.add(freeVo);
        }
        json.put("freeVos",freeVos);//树和数据
        List<ConstructionUnitDto> dtos = constructionRepository.findByUnitType("");
        for (ConstructionUnitDto c:dtos){
            freeName.add(c.getConstructionName());
        }
        json.put("dtos",dtos);//单位类型为空的

        json.put("userName",freeName);//给用户信息树用
        return json.toString();
    }

    @Override
    public String clickUserInfo() {
        JSONObject json = new JSONObject();
        List<String> freeName=new ArrayList<>();
        List<UnitTypeDto> all = unitTypeRepository.findAll();
        List<FreeVoT> freeVos=new ArrayList<>();
        for(UnitTypeDto u:all){
            FreeVoT freeVo = new FreeVoT();
            freeVo.setUserName(u.getTypeName());
            freeVo.setDtos(constructionRepository.findByUnitType(u.getTypeName()));
            freeName.add(u.getTypeName());
            freeVos.add(freeVo);
        }
        json.put("freeVos",freeVos);//树和数据
        List<ConstructionUnitDto> dtos = constructionRepository.findByUnitType("");
        for (ConstructionUnitDto c:dtos){
            freeName.add(c.getConstructionName());
        }
        json.put("dtos",dtos);//单位类型为空的

        json.put("userName",freeName);//给用户信息树用
        return json.toString();
    }

    @Override
    public String clickUnitTreeInfo(String unit) {
        if (unit == null) {
            throw new ServiceException("请选择要打开的建设单位");
        }
        List<String> data = new ArrayList<>();
        List<ConstructionUnitDto> dto = constructionRepository.findByUnitType(unit);
        for (ConstructionUnitDto d : dto) {
            data.add(d.getConstructionName());
        }

        JSONObject json = new JSONObject();
        json.put("data", data);
        return json.toString();
    }

    @Override
    public String clickLabelInfo() {
        List<OneLabelDto> dtos = oneLabelRepository.findAll();
        List<String> one = new ArrayList<>();        //获取所以的一级标签名称
        for (OneLabelDto dto : dtos) {
            one.add(dto.getLabelName());
        }

        List<TwoLabelDto> dtos1 = twoLableRepository.findAll();
        List<String> two = new ArrayList<>();
        for (TwoLabelDto dto : dtos1) {
            two.add(dto.getOneLabel());         //获取二级标签表所以的一级标签名称
        }
        List newList = two.stream().distinct().collect(Collectors.toList());    //去重后得到拥有二级标签的一级标签名称


        JSONObject json = new JSONObject();
        json.put("all", one);                //所有一级标签名称
        json.put("haveTwoLabel", newList);   //可打开的一级标签
        return json.toString();
    }

    @Override
    public String clickTwoLabelInfo(String oneLabel) {
        List<TwoLabelDto> dtos = twoLableRepository.findTwoLabelDtosByOneLabel(oneLabel);
        List<String> name = new ArrayList<>();
        for (TwoLabelDto d : dtos) {
            name.add(d.getLabelName());
        }
        JSONObject json = new JSONObject();
        json.put("data", name);
        return json.toString();
    }

    @Override
    public PageModel page(Integer page, Integer pageSize) {
        Integer one = page;
        page = (page - 1) * pageSize;
        int size = repository.findAll().size();
        List<BasicProjectDto> list = repository.page(page, pageSize);
//        PageModel model = new PageModel();
//        model.setPageNumber(one);
//        model.setPageSize(pageSize);
//        model.setTotal(size);
//        model.setRows(list);
        PageModel model = new PageModel(one, pageSize, size, list);
        return model;
    }

    /**
     * @param files 文件list
     * @param id    项目id
     */
    @Override
    public void powerfulFileSave(MultipartFile[] files, String id) throws Exception {
        for (MultipartFile file : files) {
            String url = Oss.load(file);
            FileDto fileDto = new FileDto();
            fileDto.setFileUrl(url);
            fileDto.setByMark(id);
            fileRepository.save(fileDto);
        }
    }

    @Override
    public void delectAllFile(String id, MultipartFile[] files) {
        if (files.length>0) {
            fileRepository.deleteAll(fileRepository.findByByMark(id));
        }
    }

    @Override
    public List<BasicProjectDto> inquire(String word) {

        return repository.findByMainNameContaining(word);
    }


    public void saveLabel(String[] labels, String id) {
        for (String lable : labels) {
            TheLabelDto dto = new TheLabelDto();
            dto.setLable(lable);
            dto.setByMark(id);
            theLabelRepository.save(dto);
        }
    }

    public void unitSave(String[] units, String id) {
        for (String unit : units) {
            TheUnitDto dto = new TheUnitDto();
            dto.setUnit(unit);
            dto.setByMark(id);
            theUnitRepository.save(dto);
        }
    }

    public void saveCheck(BasicProjectDto dto) {
        if (dto.getMainName() == null) {
            throw new ServiceException("主名称不能为空");
        }
        BasicProjectDto byMainName = repository.findByMainName(dto.getMainName());
        if (byMainName != null) {
            throw new ServiceException("主名称已存在，请换个主名称");
        }
        if (dto.getProjectCode() == null) {
            throw new ServiceException("项目代码不能为空");
        }
        BasicProjectDto byProjectCode = repository.findByProjectCode(dto.getProjectCode());
        if (byProjectCode != null) {
            throw new ServiceException("项目代码已存在，请换个项目代码");
        }


    }

    public void delects(String id) {
        List<TheLabelDto> byMark = theLabelRepository.findByByMark(id);
        theLabelRepository.deleteAll(byMark);
        List<TheUnitDto> byMark1 = theUnitRepository.findByByMark(id);
        theUnitRepository.deleteAll(byMark1);
        List<FileDto> byMark2 = fileRepository.findByByMark(id);
        fileRepository.deleteAll(byMark2);
    }


}
